import { isDevice } from '@/utils/commonutils'
import { uploadAttachment } from '@/api/workcard'

/* eslint-disable no-undef */
function saveAttachment(filename, dataObj) {
  if (!isDevice()) {
    return
  }
  const path = cordova.file.dataDirectory
  _saveFile(path, filename, dataObj)
}

/**
 *
 * @param {*} subfolder - workcarduid
 * @param {*} filename
 * @param {*} dataObj
 */
/* eslint-disable no-undef */
function savePhoto(workuid, filename, dataObj) {
  if (!isDevice()) {
    return
  }
  const path = cordova.file.cacheDirectory + 'ImagePicker/' + workuid + '/'
  _saveFile(path, filename, dataObj)
}

/* eslint-disable no-undef */
function _saveFile(path, filename, dataObj) {
  if (isDevice()) {
    // 如果不存在目录则创建
    const subfolder = path.substring(path.indexOf('/') + 1, path.length)
    var rootpath = cordova.file.dataDirectory
    // 如果subfolder有值，说明是存取的photo信息，photo信息在cache目录下
    if (subfolder !== '' && subfolder !== path) {
      rootpath = cordova.file.cacheDirectory
    }

    // support ios
    window.resolveLocalFileSystemURL(rootpath, function(dirEntry) {
      console.log('saved path: ' + rootpath)
      console.log('file system open: ' + dirEntry.name)
      if (rootpath === cordova.file.cacheDirectory) {
        // 看一下是否有subfolder，没有创建
        _createDirectory(dirEntry, subfolder)
      } else {
        _createFile(dirEntry, filename, dataObj)
      }
    }, _onErrorLoadFs)
  } else {
    // support chrome，safari，firefox，ie and edge
    console.log('only support mobile device, other platform does not support!')
    return
  }

  function _createDirectory(directoryEntry, dirname) {
    directoryEntry.getDirectory(dirname, { create: true, exclusive: false }, onGetDirectoryWin, onGetDirectoryFail)

    function onGetDirectoryWin(newDirEntry) {
      console.log('目录获得或创建成功：' + newDirEntry.toURL())
      _createFile(newDirEntry, filename, dataObj)
    }

    function onGetDirectoryFail(err) {
      console.log('目录创建失败：' + err)
    }
  }

  function _createFile(dirEntry, fileName, dataObj) {
    // Creates a new file or returns the file if it already exists.
    dirEntry.getFile(fileName, {
      create: true,
      exclusive: false
    }, function(fileEntry) {
      _writeFile(fileEntry, dataObj)
    }, _onErrorCreateFile)
  }

  function _writeFile(fileEntry, dataObj) {
    // Create a FileWriter object for our FileEntry (log.txt).
    fileEntry.createWriter(function(fileWriter) {
      fileWriter.onwriteend = function() {
        console.log('Successful file read...')
      }

      fileWriter.onerror = function(e) {
        console.log('Failed file read: ' + e.toString())
      }

      // If we are appending data to file, go to the end of the file.
      fileWriter.write(dataObj)
    })
  }
}

// // 把文件从cache目录拷贝到data目录
// // fullFilePath - 全路径,包括文件名，但不包含"file://"部分，例如：
// //                "/data/user/0/io.cordova.hellocordova/cache/ImagePicker/1550053764163457.jpeg"
// function copyFile(fullFilePath) {
//   if (isDevice()) {
//     // support android and ios
//     // const sourceRootPath = cordova.file.cacheDirectory + 'ImagePicker/'
//     const fileName = getFileName(fullFilePath)
//     const filePath = getFilePath(fullFilePath)
//     console.log('fullFilePath: ' + filePath)
//     console.log('fileName: ' + fileName)
//     window.resolveLocalFileSystemURL(filePath, function(dirEntry) {
//       console.log('file system open: ' + dirEntry.name)
//       _copyFile(dirEntry, fileName)
//     }, _onErrorLoadFs)
//   } else {
//     // support chrome，safari，firefox，ie and edge
//     console.log('only support mobile device, other platform does not support!')
//     return
//   }
//   function _copyFile(dirEntry, fileName) {
//     // returns the file if it already exists.
//     dirEntry.getFile(fileName, {
//       create: false,
//       exclusive: false
//     }, function(fileEntry) {
//       _readBinaryFileAndCopy(fileEntry)
//     }, _onErrorReadFile)
//   }
//
//   function _readBinaryFileAndCopy(fileEntry) {
//     fileEntry.file(function(file) {
//       var reader = new FileReader()
//       reader.onloadend = function() {
//         console.log('Successful file write: ' + this.result)
//         var blob = new Blob([new Uint8Array(this.result)], { type: 'image/jpeg' })
//         saveFile(fileEntry.name, blob)
//       }
//       reader.readAsArrayBuffer(file)
//     }, _onErrorReadFile)
//   }
// }

// fullFileName - 需要显示的文件，全路径
// files - 把需要显示的文件放在files中, files是fileEntry.toURL()
function prepareToDisplay(fullFileName, files) {
  const filePath = getFilePath(fullFileName)
  const fileName = getFileName(fullFileName)
  if (isDevice()) {
    window.resolveLocalFileSystemURL(filePath, function(fileEntry) {
      _readFile(fileEntry)
    }, _onErrorLoadFs)
  } else {
    // TODO: support chrome，safari，firefox，ie and edge
    console.log('only support ios, other platform does not support!')
    return
  }

  function _readFile(fileEntry) {
    fileEntry.getFile(fileName, {
      create: false,
      exclusive: false
    },
    function(fileEntry) {
      const file = {}
      file.name = fileEntry.name
      file.dataURL = fileEntry.toURL()
      console.log(file)
      files.push(file)
    }, _onErrorReadFile)
  }
}

function _onErrorLoadFs(e) {
  console.log('errors in _onErrorLoadFs: ' + JSON.stringify(e))
  // that.$message({
  //   message: '文件打开错误！',
  //   type: 'error'
  // })
}

function _onErrorCreateFile(e) {
  if (e.toString() !== 'Canceled') {
    console.log('errors in _onErrorCreateFile: ' + JSON.stringify(e))
    // that.$message({
    //   message: '文件打开错误！',
    //   type: 'error'
    // })
  }
}

function _onErrorReadFile(e) {
  if (e.toString() !== 'Canceled') {
    console.log('errors in _onErrorReadFile: ' + JSON.stringify(e))
    // that.$message({
    //   message: '文件打开错误！',
    //   type: 'error'
    // })
  }
}

// 根据全路径返回文件名称
// fullPath - fullpath with filename
// eg: fullPath = '/data/user/0/io.cordova.hellocordova/cache/ImagePicker/1549933907296644.jpeg'
function getFileName(fullPath) {
  if (!fullPath) { // 如果fullPath为空，返回
    return ''
  }
  if ((fullPath.lastIndexOf('/') + 1) === fullPath.length) { // 如果只有路径，不带文件名，返回为空
    return ''
  }
  return fullPath.substring(fullPath.lastIndexOf('/') + 1)
}

// 根据全路径返回文件路径
// fullPath - fullpath with filename
// eg: fullPath = '/data/user/0/io.cordova.hellocordova/cache/ImagePicker/1549933907296644.jpeg'
//  or fullPath = 'file:///data/user/0/io.cordova.hellocordova/cache/ImagePicker/1549933907296644.jpeg'
function getFilePath(fullPath) {
  if (!fullPath) { // 如果fullPath为空，返回
    return ''
  }
  if (!fullPath.startsWith('/') && !fullPath.startsWith('file:///')) { // 不支持相对路径，如果不是以'/'或'file:///'开头，返回为空
    return ''
  }

  if (fullPath.startsWith('/')) {
    return 'file://' + fullPath.substring(0, fullPath.lastIndexOf('/') + 1)
  } else {
    return fullPath.substring(0, fullPath.lastIndexOf('/') + 1)
  }
}

// directory - full file path
// fileName - attachment.path
function showFile(fileName, directory) {
  if (!isDevice()) {
    return
  }
  // const that = this
  var filePath = directory + fileName
  if (!directory) {
    filePath = cordova.file.dataDirectory + fileName
  } else if (!directory.endsWith('/')) {
    filePath = directory + '/' + fileName
  } else {
    filePath = directory + fileName
  }

  if (!filePath.startsWith('file:///')) {
    if (!filePath.startsWith('/')) {
      filePath = 'file:///' + filePath
    } else {
      filePath = 'file://' + filePath
    }
  }

  if (_isDefaultOpenFile(fileName)) {
    cordova.plugins.fileOpener2.open(
      filePath,
      'application/*',
      {
        error: function(e) {
          console.log('Error status: ' + e.status + ' - Error message: ' + e.message)
          // that.$message({
          //   message: '文件打开错误！',
          //   type: 'error'
          // })
        },
        success: function() {
          console.log('file ' + fileName + 'opened successfully')
        }
      }
    )
  } else {
    cordova.plugins.fileOpener2.showOpenWithDialog(
      filePath,
      'application/*',
      {
        error: function(e) {
          console.log('Error status: ' + e.status + ' - Error message: ' + e.message)
          // that.$message({
          //   message: '文件打开错误！',
          //   type: 'error'
          // })
        },
        success: function() {
          console.log('file opened successfully')
        }
      }
    )
  }
}

function _isDefaultOpenFile(fileName) {
  if (!fileName) {
    return false
  }
  return fileName.toLowerCase().endsWith('.jpeg') ||
         fileName.toLowerCase().endsWith('.png') ||
         fileName.toLowerCase().endsWith('.jpg') ||
         fileName.toLowerCase().endsWith('.pdf')
}

function _deleteFile(path, filename) {
  window.resolveLocalFileSystemURL(path, function(dir) {
    dir.getFile(filename, { create: false }, function(fileEntry) {
      fileEntry.remove(function() {
        console.log('remove file success: ' + filename)
      }, function(error) {
        throw error
      }, function() {
        console.log('remove failed, file does not exist: ' + filename)
      })
    })
  })
}

function deletePhoto(filename) {
  if (!isDevice()) {
    return
  }
  const path = cordova.file.cacheDirectory + 'ImagePicker/'
  _deleteFile(path, filename)
}

function deleteAttachment(filename) {
  if (!isDevice()) {
    return
  }
  const path = cordova.file.dataDirectory
  _deleteFile(path, filename)
}

function uploadPhoto(photoObject) {
  return new Promise(
    (resolve, reject) => {
      if (!isDevice()) {
        resolve({})
      }

      const fullFilePath = cordova.file.cacheDirectory + 'ImagePicker/' + photoObject.path

      window.resolveLocalFileSystemURL(
        fullFilePath, _upload, _error
      )

      function _upload(fileEntry) {
        console.log('[file]-[uploadPhoto]-got a file entry: ' + fileEntry.toURL())
        uploadAttachment(fileEntry).then(
          uid => {
            photoObject.uid = uid
            console.log('[file]-[uploadPhoto]-success upload: ' + JSON.stringify(photoObject))
            resolve(photoObject)
          },
          err => {
            reject(err)
          }
        )
      }

      function _error(err) {
        console.log('[file]-[uploadPhoto]-Error resolving fs url', JSON.stringify(err))
        reject(err)
      }
    }
  )
}

// function uploadPhotos(photoObjects) {
//   const photoUploads = []
//   photoObjects.forEach(
//     photoObj => {
//       photoUploads.push(uploadPhoto(photoObj.))
//     }
//   )
//   return Promise.all(photoUploads)
// }

export {
  saveAttachment,
  savePhoto,
  showFile,
  copyFile,
  deletePhoto,
  deleteAttachment,
  prepareToDisplay,
  getFileName,
  uploadPhoto,
  uploadPhotos
}
